package com.letme.web.controller.appletApi;

import com.letme.common.core.controller.BaseController;
import com.letme.common.core.domain.AjaxResult;
import com.letme.common.core.domain.entity.WxUser;
import com.letme.common.core.domain.model.LoginUser;
import com.letme.framework.web.service.TokenService;
import com.letme.store.domain.dto.ModifyWxUserDTO;
import com.letme.store.domain.dto.ModifyWxUserNickDTO;
import com.letme.store.service.IWxUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

/**
 * 小程序个人中心
 *
 * @Description
 * @Author lock-xq
 * @Date 2025/9/12 10:41
 **/

@Tag(name = "小程序-个人中心")
@RestController
@RequestMapping("/applet/person")
public class PersonCenterController  extends BaseController {

    @Resource
    private IWxUserService wxUserService;
    private TokenService tokenService;

    @Operation(summary ="查询当前用户的个人信息")
    @GetMapping("/queryMyInfo")
    public AjaxResult queryMyInfo(){
        return success(wxUserService.queryMyInfo());
    }

    @Operation(summary ="编辑当前用户的个人信息")
    @PostMapping("/modifyPersonalInfo")
    public AjaxResult modifyPersonalInfo(@RequestBody ModifyWxUserDTO dto){
        Boolean flag = wxUserService.modifyWxUserInfo(dto);
        if(flag){
            //更新成功刷新缓存
            refreshCache();
        }
        return toAjax(flag);
    }

    @Operation(summary ="编辑当前用户的头像、昵称")
    @PostMapping("/personalModifyNick")
    public AjaxResult personalModifyNick(@RequestBody ModifyWxUserNickDTO dto){
        Boolean flag = wxUserService.modifyWxUserNick(dto);
        if(flag){
            //更新成功刷新缓存
            refreshCache();
        }
        return toAjax(flag);
    }

    //编辑个人资料成功后刷新缓存
    private void refreshCache(){
        LoginUser loginUser = getLoginUser();
        WxUser wxUser = wxUserService.queryMyInfo();
        loginUser.setWxUser(wxUser);
        tokenService.setLoginUser(loginUser);
    }

}
